const crypto = require('crypto');

function uid(pre = '', howMany = 1, len = 4) {
  if (howMany > 9999) return false;
  const date = new Date();
  let str = date.getFullYear();
  str += ('0' + (date.getMonth() + 1)).slice(-2);
  str += ('0' + date.getDate()).slice(-2);
  str += ('0' + date.getHours()).slice(-2);
  str += ('0' + date.getMinutes()).slice(-2);
  str += ('0' + date.getSeconds()).slice(-2);
  if (!this.num || this.num.time !== str)
      this.num = { time: str, counter: 0 }
  let bd = [];
  for (let i = 0; i < howMany; i++) {
      this.num.counter++;
      const buffNum = (Array(len).join(0) + this.num.counter).slice(len * (-1));
      bd.push(pre + str + buffNum);
  }
  return bd.length > 1 ? bd : bd[0];
}

function encrypt(data) {
  if (this.key) {
    const cipher = crypto.createCipheriv(this.encryptMethod, this.key, this.iv);
    let encrypted = cipher.update(JSON.stringify(data), 'utf8', 'hex');
    encrypted += cipher.final('hex');
    return encrypted;
  }
  return data;
}

function decrypt(data) {
  if (this.key) {
    const decipher = crypto.createDecipheriv(this.encryptMethod, this.key, this.iv);
    let decrypted = decipher.update(data,'hex','utf8');
    decrypted += decipher.final('utf8');
    return JSON.parse(decrypted);
  }
  return data;
}

module.exports = {
  uid,
  encrypt,
  decrypt
}